<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { orderDetailApi, uploadImageApi } from '@/api/consult'
  import useUserStore from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'
  import { nextTick, ref } from 'vue'
  import RoomStatus from './components/room-status.vue'
  import type { Datum, MsgItem } from '../../types/room'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RateInfo from './components/rate-info.vue'

  const store = useUserStore()
  const props = defineProps<{ orderId: string; payResult: string }>()

  const msgList = ref<MsgItem[]>([])
  // 1. let定义变量和类型
  let socket: Socket

  // 1. 下包
  // 2. 导入包
  // 3. cv秘钥  桶名称  区域

  // 4. 看文档  new Cos
  // 5. uploadFile方法上传
  import COS from 'cos-js-sdk-v5'
  // console.log(COS.version);  sdk 版本需要不低于 1.8.3
  const cos = new COS({
    SecretId: 'AKIDviNp451lId4WnriRFzY0JWZVJvQl3BHJ', // sts服务下发的临时 secretId
    SecretKey: '50mQDnHwVu8CD3f3WtCbyCFD7sV0Oglc', // sts服务下发的临时 secretKey
  })

  onLoad(() => {
    if (props.payResult === 'false') {
      uni.switchTab({
        url: '/pages/my/my',
      })

      return
    }

    // 连接到服务器

    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })

    socket.on('connect', () => {
      console.log('连接成功')
    })

    // emit('statusChange')
    socket.on('statusChange', (res) => {
      getOrderInfo()
    })

    // 2. 类型✅

    // 3. 准备变量

    // 5. 根据类型, 渲染消息

    // 1. 监听服务器发来的聊天记录
    socket.on('chatMsgList', (res) => {
      console.log('收到服务器发来的聊天记录', res)
      // 4. 保存消息
      if (res.code !== 10000) return

      res.data.forEach((item: Datum) => {
        msgList.value.push(
          { msgType: 31, msg: { content: item.createTime }, id: item.createTime },
          ...item.items!
        )
      })

      // 5. 每次收到消息, 都滚动到最后一个元素的id上
      nextTick(() => {
        lastId.value = 'xxx' + (msgList.value.length - 1)
      })
      msgList.value = res.data[0].items
    })

    socket.on('receiveChatMsg', (res) => {
      console.log('收到医生发来消息', res)
      // 2. 追加到消息列表中
      msgList.value.push(res)
    })
  })
  import type { OrderDetail } from '@/types/consult'
  // 问诊订单详情
  const orderInfo = ref({} as OrderDetail)

  const getOrderInfo = async () => {
    const res = await orderDetailApi(props.orderId)
    console.log('res  ----->  ', res)

    orderInfo.value = res
  }

  onLoad(() => {
    getOrderInfo()
  })

  const contentText = ref('')
  const onSendText = () => {
    // 3. 发消息
    socket.emit('sendChatMsg', {
      // 发送人的id
      from: store.userId,
      // 医生的id
      to: orderInfo.value.docInfo.id,
      // 文字消息类型
      msgType: 1,
      msg: {
        content: contentText.value,
      },
    })

    //清空
    contentText.value = ''
  }

  const onSendImage = async () => {
    if (orderInfo.value?.status !== 3) {
      return uni.showToast({ title: '医生当前不在线!' })
    }

    // 3. uni.chooseImage
    const res = await uni.chooseVideo()
    console.log('res  ----->  ', res.tempFile)

    cos.uploadFile(
      {
        Bucket: 'ikun123-1328613558' /* 填写自己的 bucket，必须字段 */,
        Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
        Key: 'xxx.mp4' /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
        Body: res.tempFile, // 上传文件对象
        onProgress: function (progressData) {
          console.log(JSON.stringify(progressData))
        },
      },
      function (err, data) {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', 'https://' + data.Location)

          socket.emit('sendChatMsg', {
            // 发送人的id
            from: store.userId,
            // 医生的id
            to: orderInfo.value.docInfo.id,
            // 图片消息类型
            msgType: 4,
            msg: {
              picture: {
                id: 'xxx',
                url: 'https://' + data.Location,
              },
            },
          })
        }
      }
    )
  }

  //  消息滚动到最后
  // 1. 准备ref 用来保存子元素的id
  const lastId = ref('')
  //
  // 3. scrool-into-view绑定ref
</script>

<template>
  <view class="room-page">
    <RoomStatus :status="orderInfo.status" :countdown="orderInfo.countdown"></RoomStatus>
    <scroll-view
      scroll-with-animation
      :scroll-into-view="lastId"
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="(item, index) in msgList" :key="item.id" :id="'xxx' + index">
          <!-- 3. msgType为21时, 显示患者信息卡片 -->
          <!-- 4. 父传子 -->
          <PatientInfo :info="item.msg?.consultRecord" v-if="item.msgType === 21" />

          <!-- 2. 显示系统消息 -->
          <!-- 3. 判断消息类型 -->
          <!-- 4. 父传子type -->
          <!-- 5.  -->
          <NotifyInfo v-if="item.msgType! >= 31" :type="item.msgType!">
            <!-- 6. 传入系统消息内容 -->
            {{ item.msg?.content }}
          </NotifyInfo>

          <!-- 4. 传参type和信息 -->
          <MessageInfo
            :info="item"
            :type="item.msgType"
            v-if="item.msgType === 1 || item.msgType === 4"
          />

          <PrescriptionInfo v-if="item.msgType === 22" :info="item.msg!" />

          <!-- v-if="item.msgType === 23"   -->
          <RateInfo
            :order-id="orderId"
            :doc-id="orderInfo.docInfo?.id"
            v-if="item.msgType === 23 || item.msgType === 24"
            :type="item.msgType"
            :info="item.msg!"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          @confirm="onSendText"
          :disabled="orderInfo.status !== 3"
          v-model="contentText"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image" @click="onSendImage"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
